package com.starblink.login.linksocialguangaccount.ui

import android.app.Activity
import androidx.lifecycle.viewModelScope
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.android.common.utils.PasswordUtils
import com.starblink.basic.style.R
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.CommUtils
import com.starblink.rocketreserver.CheckPasswordAndBindingMutation
import com.starblink.rocketreserver.ThirdLoginMutation
import kotlinx.coroutines.launch

class LinkSocialGuangAccountVM : BaseViewModel() {
    var isAgreePolicy: Boolean = true

    /**
     * 连接三方登录账号和Guang账号
     */
    fun checkPasswordThenBind(
        email: String,
        psw: String,
        thirdLoginAccount: ThirdLoginMutation.ThirdLoginAccountV2
    ) {
        viewModelScope.launch {
            val response = SkGqlClient.skMutation(
                CheckPasswordAndBindingMutation(
                    email = email,
                    password = PasswordUtils.generatePassMD5(psw),
                    channel = thirdLoginAccount.channel,
                    thirdToken = thirdLoginAccount.thirdToken,
                    openid = thirdLoginAccount.openid ?: ""
                ),
                showDefaultLoading = true
            )
            if (response?.data != null && response.data!!.checkPasswordAndBinding.isNotEmpty()) {
                LoginManager.refreshTokenAndUserInfoAfterLoginSuccess(
                    response.data!!.checkPasswordAndBinding, // 服务器返回的GuangToken
                    onSuccess = {
                        toast(R.string.connect_success)
                        // 设置返回结果，返回登录页
                        ActivityStackManage.currentActivity().setResult(Activity.RESULT_OK)
                        ActivityStackManage.currentActivity().finish()
                    },
                    onFail = {
                        toast(CommUtils.getString(R.string.connect_fail))
                    }
                )
            }
        }
    }
}